#ifndef AXISTILEDMAP_HPP
#define AXISTILEDMAP_HPP

#include <string.h>
#include "pathfinder.h"
#include <vector>
#include <list>
#include <iostream>

struct AxisTiledGrid
{
    int x = 0;
    int y = 0;
    int gridx = 0;
    int gridy = 0;
};

class AxisTiledMapBase
{
public:
    AxisTiledMapBase()
    { }

    /**
     * @brief initMap 根据给定的数据来初始化地图大小
     * @param mapwidth  格子的横向数量
     * @param mapheight 格子的纵向数量
     * @param gridwidth 格子的横向像素长度
     * @param gridheight 格子的纵向像素长度
     */
    virtual void initMap(int mapwidth, int mapheight, int gridwidth, int gridheight)
    {
        _mapwidth = mapwidth;
        _mapheight = mapheight;
        _gridwidth = gridwidth;
        _gridheight = gridheight;

        for (int r = 0; r < _mapheight; ++r )
        {
            std::vector<int> l;
            for ( int c = 0; c < _mapwidth; ++c )
            {
                l.push_back(0);
            }
            maze.push_back(l);
        }
        _astar.InitAstar(maze);

        /* 初始化地图格子 */
        AxisTiledGrid* tmpptr = new AxisTiledGrid[_mapwidth * _mapheight];
        _grids = new AxisTiledGrid* [_mapheight];

        for ( int r = 0; r < _mapheight; ++r )
        {
            AxisTiledGrid* widthptr = tmpptr + (r * _mapwidth);
            memset(widthptr, 0, sizeof(AxisTiledGrid) * _mapwidth);
            _grids[r] = widthptr;

            for ( int c = 0; c < _mapwidth; ++c )
            {
                _grids[r][c].gridx = c;
                _grids[r][c].gridy = r;
            }
        }
    }

    virtual ~AxisTiledMapBase()
    {
        if ( nullptr != _grids )
        {
            delete[] _grids[0];
            delete[] _grids;
            _grids = nullptr;
        }
    }

    void tileToScreenCoords(float x, float y, float& rx, float& ry)
    {
        const int tilewidth = getGridWidth();
        const int tileheight= getGridHeight();
        const int originx = getMapHeight() * tilewidth / 2;

        rx = (x -y) * tilewidth / 2 + originx;
        ry = (x + y) * tileheight / 2;
    }

    AxisTiledGrid** getGrids() const
    {
        return _grids;
    }

    int getMapWidth() const { return _mapwidth; }
    int getMapHeight() const { return _mapheight; }
    int getGridWidth() const { return _gridwidth; }
    int getGridHeight() const { return _gridheight; }

    bool isValidGrid(int gridx, int gridy)
    {
        if ( gridx >= _mapwidth || gridx < 0 )
            return false;
        if ( gridy >= _mapheight || gridy < 0 )
            return false;
        return true;
    }

    Astar getAstar() const { return _astar; }

protected:
    AxisTiledGrid** _grids = nullptr;

    int _mapwidth = 0;
    int _mapheight= 0;
    int _gridwidth= 0;
    int _gridheight=0;

    Astar _astar;
    std::vector<std::vector<int>> maze;


};

#endif // AXISTILEDMAP_HPP
